# encoding=utf8
import sys
import math
reload(sys)
sys.setdefaultencoding('utf8')
from ..hangbiaoMessageAnalysis import*

class OBD_03:
	#*****************************************************************************#
	#*Description：全局变量定义
	#*****************************************************************************#
	AnalysisSwitch=1    #解析开关，1：按17691法规解析      2：按17691法规纠正后的解析
	InfoPrintStruct=[]  #02信息数据结构
	result=[]           #输出结果
	FaultTol=0          #故障码总数
	OBDmesg=[["数据采集时间:","6"],["信息流水号:","2"],["信息类型标志:","1"],["OBD诊断协议:","1"],["MIL状态:","1"],["诊断支持状态:","2"],["诊断就绪状态:","2"],["车辆识别码:","17"],["软件标定识别号:","18"],["标定验证码（CVN）:","18"],["IUPR值:","36"],["故障码总数:","1"],["故障码列表:","-1"],["信息类型标志:","1"],["车速:","2"],["大气压力（直接测量或估计值）:","1"],["发动机净输出扭矩:","1"],["摩擦扭矩:","1"],["发动机转速:","2"],["发动机燃料流量:","2"],["SCR上游NOx传感器输出值:","2"],["SCR下游NOx传感器输出值:","2"],["反应剂余量:","1"],["进气量:","2"],["SCR入口温度","2"],["SCR出口温度","2"],["DPF压差","2"],["发动机冷却液温度:","1"],["油箱液位:","1"],["定位状态:","1"],["经度:","4"],["纬度:","4"],["累计里程:","4"],["信息类型标志:","1"],["发动机扭矩模式:","1"],["油门踏板:","1"],["累计油耗(总油耗):","4"],["尿素箱温度:","1"],["实际尿素喷射量:","4"],["累计尿素消耗(总尿素消耗):","4"],["DPF排气温度:","2"]]

	#*****************************************************************************#
	#*Description：逻辑处理通道
	#*****************************************************************************#
	def LogicAisle(self, protocolStr, header):
		self.result = header
		self.InfoPrintStruct=[]
		name = ""
		len = 0
		offset = 0
		i = 0
		flag = 0
		msgoffset = 0
		self.init()                                          #初始化
		for t in self.InfoPrintStruct:                       #轮询打印
			name = t['name']                                 #获取信号名称
			len = int(t['len'])                              #获取信号字段长度
			i += 1;                                          #轮询次数

			if name == "信息类型标志:":						 #解析信息类型标志
				try:
					flag = int(protocolStr[offset:(offset+len*2)],16)
					print("flag = %02x"%flag)
				except:
					flag = 0xFFFF
					print("err flag = %s"%protocolStr[offset:offset+len*2])

			if flag == 0x01:								#根据信息类型标志找到偏移
				msgoffset = 3
			elif flag == 0x02:
				msgoffset = 14
			elif flag == 0x80:
				msgoffset = 34
			elif flag == 0xFFFF:
				msgoffset = 65535
			print("msgoffset = %d, i = %d"%(msgoffset,i))

			if i < msgoffset:								#信息类型不对则不解析
				continue

			if len == -1:                                    #故障码长度获取
				if FaultTol >= 0xFE:
					len = 0
				else:
					len = FaultTol * 4
			#print type(t['fun'])
			offset += t['fun'](name, protocolStr[offset:], len)   #字段解析,并更新偏移

	#*****************************************************************************#
	#*Description：02信息数据结构列表添加
	#*****************************************************************************#
	def AddList(self, name, len):
		self.InfoPrintStruct.append({
			'name': name,
			'len':len,
			'fun': self.FieldAnalysis,
		})

	#*****************************************************************************#
	#*Description：初始化
	#*****************************************************************************#
	def init(self):
		for i in range(len(self.OBDmesg)):
			#print ("OBDmesg0 = %s",self.OBDmesg[i][0])
			#print type(self.OBDmesg[i][0])
			#print ("OBDmesg1 = %s",self.OBDmesg[i][1])
			#print type(self.OBDmesg[i][1])
			self.AddList(self.OBDmesg[i][0],self.OBDmesg[i][1])

	#*****************************************************************************#
	#*Description：数据字段解析
	#*****************************************************************************#
	def FieldAnalysis(self, name, string, len):
		offset = len * 2
		global FaultTol                   #修改全局变量值，此处必须加global修饰

		if name == "数据采集时间:":
			self.result.append(name+"20"+str(int(string[0:2],16))+"年"+str(int(string[2:4],16))+"月"+str(int(string[4:6],16))+
			"日"+str(int(string[6:8],16))+"时"+str(int(string[8:10],16))+"分"+str(int(string[10:12],16))+"秒"+"\n")
		elif len ==0 and name == "故障码列表:":
			len = 0
		elif len == 0 and name != "故障码列表:":
			self.result.append(name + "\n")
		else:
			self.result.append(name + string[0:offset] + "\n")
			
		if name == "故障码总数:":         #记录故障码总数
			print("FaultTol = %s"%string[0:offset])
			try:
		   		FaultTol = int(string[0:offset],16)
			except:
				FaultTol = 0xFF
				print("FaultTol int trans err! %s"%string[0:offset])

		return offset
